package ghostbanlistd;

import java.nio.ByteBuffer;

public class Util {
	public static String hexEncode(byte[] input) {
		if (input == null || input.length == 0) {
			return "";
		}

		int inputLength = input.length;
		StringBuilder output = new StringBuilder(inputLength * 2);

		for (int i = 0; i < inputLength; i++) {
			int next = input[i] & 0xff;
			if (next < 0x10) {
				output.append("0");
			}

			output.append(Integer.toHexString(next));
		}

		return output.toString();
	}

	public static byte[] shortToByteArray(short s) {
		return new byte[] { (byte) ((s & 0xFF00) >> 8), (byte) (s & 0x00FF) };
	}
	
	public static int unsignedShort(short s) {
		byte[] array = shortToByteArray(s);
		int b1 = (0x000000FF & ((int) array[0]));
		int b2 = (0x000000FF & ((int) array[1]));
		return (b1 << 8 | b2);
	}

	public static int unsignedByte(byte b) {
		return (0x000000FF & ((int)b));
	}
	
	public static int byteArrayToInt(byte[] b) {
		return byteArrayToInt(b, 0);
	}
	
	public static int byteArrayToInt(byte[] b, int offset) {
		int value = 0;
		for (int i = 0; i < 4; i++) {
			int shift = (4 - 1 - i) * 8;
			value += (b[i + offset] & 0x000000FF) << shift;
		}
		return value;
	}
	
	public static final byte[] intToByteArray(int value) {
        return new byte[] {
                (byte)(value >>> 24),
                (byte)(value >>> 16),
                (byte)(value >>> 8),
                (byte)value};
	}
	
	public static long byteArrayToLong(byte[] b, int offset, int length) {
		long value = 0;
		for (int i = 0; i < length && i < b.length; i++) {
		   value = (value << 8) + (b[i + offset] & 0xff);
		}
		
		return value;
	}

	public static String getTerminatedString(ByteBuffer buf) {
		return new String(getTerminatedArray(buf));
	}

	public static byte[] getTerminatedArray(ByteBuffer buf) {
		int start = buf.position();

		while(buf.get() != 0) {}
		int end = buf.position();

		byte[] bytes = new byte[end - start - 1]; //don't include terminator
		buf.position(start);
		buf.get(bytes);

		//put position after array
		buf.position(end); //skip terminator

		return bytes;
	}
}
